package com.wey.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class RequestLoggingFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(RequestLoggingFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化代码
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        logger.info("Request URL: {}", httpRequest.getRequestURL());
        logger.info("HTTP Method: {}", httpRequest.getMethod());
        logger.info("Request Headers: {}", httpRequest.getHeaderNames());
        logger.info("Request Parameters: {}", httpRequest.getParameterMap());

        chain.doFilter(request, response);

        logger.info("Response Status: {}", httpResponse.getStatus());
        logger.info("Response Headers: {}", httpResponse.getHeaderNames());
    }

    @Override
    public void destroy() {
        // 销毁代码
    }
}
